package org.gdstash.db;

import java.sql.*;

public class GDDBUtil {
    public static boolean doesExist(final String url) {
        boolean exists = false;
        try {
            final Connection conn = DriverManager.getConnection(url + "create=false");
            exists = true;
            conn.close();
        } catch (SQLException ex) {
        }
        return exists;
    }

    public static boolean tableExists(final String tablename) throws SQLException {
        boolean found = false;
        try (final Connection conn = GDDBData.getConnection()) {
            found = tableExists(conn, tablename);
            conn.commit();
        } catch (SQLException ex) {
            throw ex;
        }
        return found;
    }

    public static boolean tableExists(final Connection conn, final String tablename) throws SQLException {
        boolean found = false;
        final DatabaseMetaData meta = conn.getMetaData();
        try (final ResultSet rs = meta.getTables(null, null, tablename, null)) {
            while (rs.next()) {
                final String name = rs.getString(3);
                if (name.equals(tablename)) {
                    found = true;
                    break;
                }
            }
        } catch (SQLException ex) {
            found = false;
            throw ex;
        }
        return found;
    }
}
